package 牛客题霸;

import java.util.*;

public class 字符串出现次数的TopK问题 {

    public String[][] topKstrings(String[] strings, int k) {
        String[][] resultStr = new String[k][2];
        if (strings == null || strings.length <= 0) {
            return resultStr;
        }
        Map<String, Integer> map = new TreeMap<>();
        for (int i = 0; i < strings.length; i++) {
            if (map.containsKey(strings[i])) {
                map.put(strings[i], map.get(strings[i]) + 1);
            } else {
                map.put(strings[i], 1);
            }
        }
        List<String> res = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            res.add(entry.getKey());
        }
        Collections.sort(res,(o1,o2) ->{
            return map.get(o1) == map.get(o2) ? o1.compareTo(o2) : map.get(o2) - map.get(o1);
        });

        for (int i = 0; i < k; i++) {
            resultStr[i][0] = res.get(i);
            resultStr[i][1] = String.valueOf(map.get(res.get(i)));
        }
        return resultStr;
    }

    public static void main(String[] args) {

    }
}
